<template>
  <div>
    <Card title="OAuth2" class="w-1/2 !m-10px min-w-700px">
      <Checkbox v-model:checked="data.enabled" @change="change">启用OAuth2设置</Checkbox>
      <Collapse
        expandIconPosition="right"
        v-for="(oauth2Param, index) in data.oauth2ParamsInfos"
        :key="index"
        v-show="data.enabled"
        class="!mt-24px"
      >
        <CollapsePanel
          :header="showPanelHeader(oauth2Param.domainInfos)"
          :forceRender="true"
          class="flex flex-col"
        >
          <template #extra>
            <Button type="text" shape="circle" @click.stop="deleteOauth2Param(index)">
              <Icon :icon="ICON.DELETE" class="!text-24px" />
            </Button>
          </template>
          <Form :model="oauth2Param" layout="vertical" ref="forms" :scrollToFirstError="true">
            <Tabs :centered="true">
              <TabPane tab="域名" key="domain" :forceRender="true" class="flex flex-col">
                <Row
                  v-for="(domain, domainIndex) in oauth2Param.domainInfos"
                  :key="domainIndex"
                  :gutter="20"
                >
                  <Col span="5">
                    <FormItem :name="['domainInfos', domainIndex, 'scheme']" label="协议">
                      <Select
                        v-model:value="domain.scheme"
                        class="!min-w-120px"
                        @change="domainSchemeChange(index, domainIndex)"
                      >
                        <SelectOption value="HTTP">HTTP</SelectOption>
                        <SelectOption value="HTTPS">HTTPS</SelectOption>
                        <SelectOption value="MIXED">HTTP+HTTPS</SelectOption>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="5">
                    <FormItem
                      :name="['domainInfos', domainIndex, 'name']"
                      label="域名"
                      :required="true"
                      :rules="[
                        {
                          validator: () => validatorName(oauth2Param, domainIndex),
                        },
                        {
                          pattern: /^(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?$/,
                          message: '域名不应包含符号 “/” 和 “:”。例：thingsboard.io',
                        },
                      ]"
                    >
                      <Input v-model:value="domain.name" placeholder="域名" @change="change" />
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="重定向URL模板">
                      <Input
                        :value="domain.name ? `https://${domain.name}/login/oauth2/code/` : null!"
                        v-show="domain.scheme != 'HTTP'"
                      >
                        <template #suffix>
                          <Button
                            type="text"
                            shape="circle"
                            @click="copy(domain.name, 'https')"
                            size="small"
                          >
                            <Icon icon="ant-design:copy-outlined" />
                          </Button>
                        </template>
                      </Input>
                      <Input
                        :value="domain.name ? `http://${domain.name}/login/oauth2/code/` : null!"
                        v-show="domain.scheme != 'HTTPS'"
                      >
                        <template #suffix>
                          <Button
                            type="text"
                            shape="circle"
                            @click="copy(domain.name, 'http')"
                            size="small"
                          >
                            <Icon icon="ant-design:copy-outlined" />
                          </Button>
                        </template>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="2" class="!flex !items-center">
                    <Button
                      type="text"
                      shape="circle"
                      @click="deleteDomain(index, domainIndex)"
                      :disabled="oauth2Param.domainInfos.length > 1 ? false : true"
                      ><Icon :icon="ICON.X_DELETE" class="!text-24px"
                    /></Button>
                  </Col>
                </Row>
                <div>
                  <Button type="primary" class="float-right" @click="addDomain(index)"
                    >添加域</Button
                  >
                </div>
              </TabPane>
              <TabPane tab="移动端应用" key="mobile" :forceRender="true" class="flex flex-col">
                <span
                  class="flex place-content-center text-lg font-normal text-zinc-400 mb-24px"
                  v-show="oauth2Param.mobileInfos.length === 0"
                  >未配置应用程序</span
                >
                <Row
                  v-for="(mobile, mobileIndex) in oauth2Param.mobileInfos"
                  :key="mobileIndex"
                  :gutter="20"
                >
                  <Col span="11">
                    <FormItem
                      :name="['mobileInfos', mobileIndex, 'pkgName']"
                      label="应用程序包"
                      extra="Android:应用程序ID,iOS:产品标识符"
                      :required="true"
                      :rules="[
                        {
                          validator: () => validatorPkgName(mobileIndex, oauth2Param),
                        },
                      ]"
                    >
                      <Input
                        v-model:value="mobile.pkgName"
                        placeholder="应用程序包"
                        @change="change"
                      />
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem
                      :name="['mobileInfos', mobileIndex, 'appSecret']"
                      label="应用程序密钥"
                      :required="true"
                      :rules="[
                        {
                          pattern: /^[A-Za-z0-9]{16,2048}$/,
                          message:
                            '应用程序密钥必须只包含字母和数字字符，并且长度必须介于16到2048个字符之间。',
                        },
                      ]"
                    >
                      <Input
                        v-model:value="mobile.appSecret"
                        placeholder="应用程序密钥"
                        @change="change"
                      >
                        <template #suffix>
                          <Button
                            type="text"
                            shape="circle"
                            @click="copy(mobile.appSecret)"
                            size="small"
                          >
                            <Icon icon="ant-design:copy-outlined" />
                          </Button>
                        </template>
                      </Input>
                    </FormItem>
                  </Col>
                  <Col span="2" class="!flex !items-center"
                    ><Button type="text" shape="circle" @click="deleteMobile(index, mobileIndex)"
                      ><Icon :icon="ICON.X_DELETE" class="!text-24px" /></Button
                  ></Col>
                </Row>
                <div>
                  <Button type="primary" class="float-right" @click="addMobile(index)"
                    >添加应用程序</Button
                  >
                </div>
              </TabPane>
            </Tabs>
            <p class="text-base font-normal leading-7 mt-24px mb-12px">供应商</p>
            <Collapse
              expandIconPosition="right"
              v-for="(client, clientIndex) in oauth2Param.clientRegistrations"
              :key="clientIndex"
              class="!mt-24px"
            >
              <CollapsePanel :forceRender="true" :header="client.additionalInfo.providerName">
                <template #extra>
                  <Button
                    type="text"
                    shape="circle"
                    @click.stop="deleteClient(index, clientIndex)"
                    :disabled="oauth2Param.clientRegistrations.length > 1 ? false : true"
                  >
                    <Icon :icon="ICON.DELETE" class="!text-24px" />
                  </Button>
                </template>
                <Row :gutter="20">
                  <Col span="12">
                    <FormItem
                      :name="['clientRegistrations', clientIndex, 'additionalInfo', 'providerName']"
                      label="Login Provider"
                    >
                      <Select
                        v-model:value="client.additionalInfo.providerName"
                        @change="(value:string) => providerNameChange(value, index, clientIndex)"
                      >
                        <SelectOption value="Google">Google</SelectOption>
                        <SelectOption value="Apple">Apple</SelectOption>
                        <SelectOption value="Custom">Custom</SelectOption>
                        <SelectOption value="Facebook">Facebook</SelectOption>
                        <SelectOption value="Github">Github</SelectOption>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem
                      :name="['clientRegistrations', clientIndex, 'platforms']"
                      label="允许平台"
                    >
                      <Select
                        v-model:value="client.platforms"
                        mode="multiple"
                        placeholder="所有平台"
                        @change="change"
                      >
                        <SelectOption value="WEB">Web</SelectOption>
                        <SelectOption value="ANDROID">Android</SelectOption>
                        <SelectOption value="IOS">iOS</SelectOption>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem
                      :name="['clientRegistrations', clientIndex, 'clientId']"
                      label="客户端 ID"
                      :required="true"
                    >
                      <Input
                        v-model:value="client.clientId"
                        placeholder="客户端 ID"
                        @change="change"
                      />
                    </FormItem>
                  </Col>
                  <Col span="12"
                    ><FormItem
                      :name="['clientRegistrations', clientIndex, 'clientSecret']"
                      label="客户机密"
                      :required="true"
                    >
                      <Input
                        v-model:value="client.clientSecret"
                        placeholder="客户机密"
                        @change="change"
                    /></FormItem>
                  </Col>
                </Row>
                <Collapse expandIconPosition="right">
                  <CollapsePanel :forceRender="true" header="自定义设置">
                    <Tabs :centered="true">
                      <TabPane tab="基本设置" key="setting" :forceRender="true">
                        <Row :gutter="20">
                          <Col span="12">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'accessTokenUri']"
                              label="访问令牌URI"
                              :required="true"
                              :rules="[
                                {
                                  pattern: urlPattern,
                                  message: '无效的URI格式',
                                },
                              ]"
                            >
                              <Input
                                v-model:value="client.accessTokenUri"
                                placeholder="访问令牌URI"
                                @change="change"
                            /></FormItem>
                          </Col>
                          <Col span="12">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'authorizationUri']"
                              label="授权URL"
                              :required="true"
                              :rules="[
                                {
                                  pattern: urlPattern,
                                  message: '无效的URI格式',
                                },
                              ]"
                            >
                              <Input
                                v-model:value="client.authorizationUri"
                                placeholder="授权URI"
                                @change="change"
                            /></FormItem>
                          </Col>
                          <Col span="12">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'jwkSetUri']"
                              label="JSON Web Key URI"
                              :rules="[
                                {
                                  pattern: urlPattern,
                                  message: '无效的URI格式',
                                },
                              ]"
                            >
                              <Input
                                v-model:value="client.jwkSetUri"
                                placeholder="JSON Web Key URL"
                                @change="change"
                            /></FormItem>
                          </Col>
                          <Col span="12">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'userInfoUri']"
                              label="用户信息URI"
                              :rules="[
                                {
                                  pattern: urlPattern,
                                  message: '无效的URI格式',
                                },
                              ]"
                            >
                              <Input
                                v-model:value="client.userInfoUri"
                                placeholder="用户信息URI"
                                @change="change"
                            /></FormItem>
                          </Col>
                          <Col span="24">
                            <FormItem
                              :name="[
                                'clientRegistrations',
                                clientIndex,
                                'clientAuthenticationMethod',
                              ]"
                              label="客户端身份验证方法"
                            >
                              <Select
                                v-model:value="client.clientAuthenticationMethod"
                                @change="change"
                              >
                                <SelectOption value="BASIC">BASIC</SelectOption>
                                <SelectOption value="POST">POST</SelectOption>
                              </Select>
                            </FormItem>
                          </Col>
                          <Col span="12" v-if="client.additionalInfo.providerName === 'Custom'">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'loginButtonLabel']"
                              label="provider标签"
                              :required="true"
                            >
                              <Input
                                v-model:value="client.loginButtonLabel"
                                placeholder="使用$(Provider label)登录"
                                @change="change"
                            /></FormItem>
                          </Col>
                          <Col span="12" v-if="client.additionalInfo.providerName === 'Custom'">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'loginButtonIcon']"
                              label="登录按钮图标"
                            >
                              <Input
                                v-model:value="client.loginButtonIcon"
                                placeholder="登录按钮图标"
                                @change="change"
                            /></FormItem>
                          </Col>
                          <Col span="24">
                            <FormItem
                              :name="[
                                'clientRegistrations',
                                clientIndex,
                                'mapperConfig',
                                'allowUserCreation',
                              ]"
                            >
                              <Checkbox
                                v-model:checked="client.mapperConfig.allowUserCreation"
                                @change="change"
                              >
                                允许用户创建
                              </Checkbox>
                            </FormItem>
                          </Col>
                          <Col span="24">
                            <FormItem
                              :name="[
                                'clientRegistrations',
                                clientIndex,
                                'mapperConfig',
                                'activateUser',
                              ]"
                            >
                              <Checkbox
                                v-model:checked="client.mapperConfig.activateUser"
                                @change="change"
                              >
                                激活用户
                              </Checkbox>
                            </FormItem>
                          </Col>
                          <Col span="24">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'scope']"
                              :required="true"
                            >
                              <InputList
                                inputTitle="范围"
                                :initInputDataList="client.scope"
                                :dataChange="client.scope"
                                @getInputDataList="
                                  (result) => InputListChange(result, index, clientIndex)
                                "
                              />
                            </FormItem>
                          </Col>
                        </Row>
                      </TabPane>
                      <TabPane tab="Mapper" key="mapper" :forceRender="true">
                        <Row :gutter="20">
                          <Col span="24">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'userNameAttributeName']"
                              label="用户名属性键"
                              :required="true"
                            >
                              <Input
                                v-model:value="client.userNameAttributeName"
                                placeholder="用户名属性键"
                                @change="change"
                              />
                            </FormItem>
                          </Col>
                          <Col span="24">
                            <FormItem
                              :name="['clientRegistrations', clientIndex, 'mapperConfig', 'type']"
                              label="映射器类型"
                            >
                              <Select v-model:value="client.mapperConfig.type" @change="change">
                                <SelectOption value="BASIC">BASIC</SelectOption>
                                <SelectOption value="CUSTOM">CUSTOM</SelectOption>
                                <SelectOption value="GITHUB">GITHUB</SelectOption>
                                <SelectOption value="APPLE">APPLE</SelectOption>
                              </Select>
                            </FormItem>
                          </Col>
                          <template v-if="client.mapperConfig.type != 'CUSTOM'">
                            <Col
                              span="24"
                              v-if="
                                client.mapperConfig.type === 'APPLE' ||
                                client.mapperConfig.type === 'BASIC'
                              "
                            >
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'emailAttributeKey',
                                ]"
                                label="电子邮件属性键"
                                :required="true"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.basic.emailAttributeKey"
                                  placeholder="电子邮件属性键"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="12">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'firstNameAttributeKey',
                                ]"
                                label="名字属性键"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.basic.firstNameAttributeKey"
                                  placeholder="名字属性键"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="12">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'lastNameAttributeKey',
                                ]"
                                label="姓氏属性键"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.basic.lastNameAttributeKey"
                                  placeholder="姓氏属性键"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col
                              :span="
                                client.mapperConfig.basic.tenantNameStrategy === 'CUSTOM' ? 12 : 24
                              "
                            >
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'tenantNameStrategy',
                                ]"
                                label="租户名称策略"
                              >
                                <Select
                                  v-model:value="client.mapperConfig.basic.tenantNameStrategy"
                                  placeholder="租户名称策略"
                                  @change="change"
                                >
                                  <SelectOption value="DOMAIN">DOMAIN</SelectOption>
                                  <SelectOption value="EMAIL">EMAIL</SelectOption>
                                  <SelectOption value="CUSTOM">CUSTOM</SelectOption>
                                </Select>
                              </FormItem>
                            </Col>
                            <Col
                              span="12"
                              v-if="client.mapperConfig.basic.tenantNameStrategy === 'CUSTOM'"
                            >
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'tenantNamePattern',
                                ]"
                                label="租户名称模式"
                                :required="true"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.basic.tenantNamePattern"
                                  placeholder="租户名称模式"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="24">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'customerNamePattern',
                                ]"
                                label="客户名称模式"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.basic.customerNamePattern"
                                  placeholder="客户名称模式"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="12">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'defaultDashboardName',
                                ]"
                                label="默认仪表盘名称"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.basic.defaultDashboardName"
                                  placeholder="默认仪表盘名称"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="12">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'basic',
                                  'alwaysFullScreen',
                                ]"
                                label=" "
                              >
                                <Checkbox
                                  v-model:checked="client.mapperConfig.basic.alwaysFullScreen"
                                  @change="change"
                                  >始终全屏</Checkbox
                                >
                              </FormItem>
                            </Col>
                          </template>
                          <template v-if="client.mapperConfig.type === 'CUSTOM'">
                            <Col span="24">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'custom',
                                  'url',
                                ]"
                                label="统一资源定位地址"
                                :required="true"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.custom.url"
                                  placeholder="统一资源定位地址"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="12">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'custom',
                                  'username',
                                ]"
                                label="用户名"
                              >
                                <Input
                                  v-model:value="client.mapperConfig.custom.username"
                                  placeholder="用户名"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                            <Col span="12">
                              <FormItem
                                :name="[
                                  'clientRegistrations',
                                  clientIndex,
                                  'mapperConfig',
                                  'custom',
                                  'password',
                                ]"
                                label="密码"
                              >
                                <InputPassword
                                  v-model:value="client.mapperConfig.custom.password"
                                  placeholder="密码"
                                  @change="change"
                                />
                              </FormItem>
                            </Col>
                          </template>
                        </Row>
                      </TabPane>
                    </Tabs>
                  </CollapsePanel>
                </Collapse>
              </CollapsePanel>
            </Collapse>
            <Button type="primary" class="float-right my-24px" @click="addClient(index)"
              >添加供应商</Button
            >
          </Form>
        </CollapsePanel>
      </Collapse>
      <div class="flex flex-row justify-end mt-24px">
        <Button
          type="primary"
          v-show="data.enabled"
          class="flex items-center mr-12px"
          @click="addOauth2ParamsItem"
        >
          <Icon :icon="ICON.PLUS" />添加
        </Button>
        <Button type="primary" @click="save" :disabled="!isEdit">保存</Button>
      </div>
    </Card>
  </div>
</template>

<script lang="ts" setup>
  import {
    Card,
    Checkbox,
    Collapse,
    CollapsePanel,
    Tabs,
    TabPane,
    Form,
    FormItem,
    Row,
    Col,
    Select,
    SelectOption,
    Input,
    InputPassword,
    Button,
  } from 'ant-design-vue';
  import { onMounted, ref, watch } from 'vue';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getOauth2Setting, postOauth2Setting } from '/@/api/thingsborad/security/oauth2/oauth2';
  import InputList from '/@/components/thingsborad/sharedComponents/modules/InputList.vue';
  import { useSystemStatusStoreWithOut } from '/@/store/modules/thingsboard/systemStatus';
  import {
    GoogleClientItem,
    AppleClientItem,
    GithubClientItem,
    FacebookClientItem,
    CustomClientItem,
  } from './oauth2.data';
  import _ from 'lodash';
  const urlPattern =
    /^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.,?+=&%@\-/]*)?$/;
  let forms = ref<Array<Recordable>>([]);
  let data = ref<Recordable>({
    enabled: false,
    oauth2ParamsInfos: [],
  });
  let domainItem = ref<Recordable>({
    scheme: 'HTTPS',
    name: null,
  });
  let mobileItem = ref<Recordable>({
    appSecret: null,
    pkgName: null,
  });
  let isEdit = ref(false);
  //域名验证
  function validatorName(data: Recordable, domainIndex: number) {
    let name = JSON.stringify(data.domainInfos[domainIndex]);
    let count = data.domainInfos.filter((item: Recordable) => JSON.stringify(item) === name).length;
    if (count >= 2) {
      return Promise.reject(new Error('域名和协议必须是唯一的'));
    } else {
      return Promise.resolve();
    }
  }
  //应用程序包验证
  function validatorPkgName(mobileIndex: number, data: Recordable) {
    let name = data.mobileInfos[mobileIndex].pkgName;
    let count = data.mobileInfos.filter((item: Recordable) => item.pkgName === name).length;
    if (count >= 2) {
      return Promise.reject(new Error('应用程序包必须是唯一的'));
    } else {
      return Promise.resolve();
    }
  }
  onMounted(async () => {
    let res: Recordable = {};
    try {
      res = await getOauth2Setting();
    } catch (e) {
      console.error('获取OAuth2设置失败', res);
    }
    res.oauth2ParamsInfos.map((item: Recordable) => {
      item.clientRegistrations.map((client: Recordable) => {
        if (!client.mapperConfig.custom) {
          client.mapperConfig.custom = {
            password: null,
            sendToken: false,
            url: null,
            username: null,
          };
        }
        client.scope = client.scope.map((value: Recordable) => ({
          text: value,
        }));
      });
    });
    data.value = res;
  });
  const { clipboardRef } = useCopyToClipboard();
  const { createMessage, createConfirm } = useMessage();
  // 添加OAuth2设置
  function addOauth2ParamsItem() {
    let param: Recordable = { domainInfos: [], mobileInfos: [], clientRegistrations: [] };
    param.domainInfos.push({ ...domainItem.value, name: window.location.hostname });
    param.clientRegistrations.push({ ...GoogleClientItem });
    data.value.oauth2ParamsInfos.push(param);
    isEdit.value = true;
  }
  // 删除OAuth2设置
  function deleteOauth2Param(index: number) {
    let name = showPanelHeader(data.value.oauth2ParamsInfos[index].domainInfos);
    createConfirm({
      iconType: 'info',
      title: `确定要删除域'` + name + `'的设置吗？`,
      content: '请注意：确认后，域和所有provider data将不可恢复',
      onOk: () => {
        data.value.oauth2ParamsInfos.splice(index, 1);
        isEdit.value = true;
      },
    });
  }
  // 添加域名设置
  function addDomain(index: number) {
    data.value.oauth2ParamsInfos[index].domainInfos.push({ ...domainItem.value });
    isEdit.value = true;
  }
  // 删除域名设置
  function deleteDomain(index: number, domainIndex: number) {
    data.value.oauth2ParamsInfos[index].domainInfos.splice(domainIndex, 1);
    isEdit.value = true;
  }
  // 添加移动端应用设置
  function addMobile(index: number) {
    data.value.oauth2ParamsInfos[index].mobileInfos.push({
      ...mobileItem.value,
      appSecret: randomAlphanumeric(24),
    });
    isEdit.value = true;
  }
  // 删除移动端应用设置
  function deleteMobile(index: number, mobileIndex: number) {
    data.value.oauth2ParamsInfos[index].mobileInfos.splice(mobileIndex, 1);
    isEdit.value = true;
  }
  //添加供应商配置
  function addClient(index: number) {
    data.value.oauth2ParamsInfos[index].clientRegistrations.push(_.cloneDeep(GoogleClientItem));
    isEdit.value = true;
  }
  //删除供应商配置
  function deleteClient(index: number, clientIndex: number) {
    let name =
      data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex].additionalInfo
        .providerName;
    createConfirm({
      iconType: 'info',
      title: `确定要删除provider'` + name + `'的设置吗？`,
      content: '请注意：确认后provider data将不可恢复',
      onOk: () => {
        data.value.oauth2ParamsInfos[index].clientRegistrations.splice(clientIndex, 1);
      },
    });
    isEdit.value = true;
  }
  //复制
  function copy(data: string, string?: string) {
    if (data) {
      if (string === 'https') {
        clipboardRef.value = 'https://' + data + '/login/oauth2/code/';
      } else if (string === 'http') {
        clipboardRef.value = 'http://' + data + '/login/oauth2/code/';
      } else {
        clipboardRef.value = data;
      }
    } else {
      clipboardRef.value = '';
    }

    createMessage.success('复制成功');
  }
  //折叠面板标题
  function showPanelHeader(data: Array<Recordable>) {
    return data.map((item: Recordable) => item.name).join(',');
  }
  const alphanumericCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const alphanumericCharactersLength = alphanumericCharacters.length;
  //密钥生成
  function randomAlphanumeric(length: number): string {
    let result = '';
    for (let i = 0; i < length; i++) {
      result += alphanumericCharacters.charAt(
        Math.floor(Math.random() * alphanumericCharactersLength),
      );
    }
    return result;
  }
  //范围更改
  function InputListChange(result: any, index: number, clientIndex: number) {
    data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex].scope = result;
    isEdit.value = true;
  }
  //供应商更改
  function providerNameChange(change: string, index: number, clientIndex: number) {
    if (change === 'Google') {
      data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex] = {
        ...GoogleClientItem,
      };
    } else if (change === 'Apple') {
      data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex] = {
        ...AppleClientItem,
      };
    } else if (change === 'Custom') {
      data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex] = {
        ...CustomClientItem,
      };
    } else if (change === 'Facebook') {
      data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex] = {
        ...FacebookClientItem,
      };
    } else if (change === 'Github') {
      data.value.oauth2ParamsInfos[index].clientRegistrations[clientIndex] = {
        ...GithubClientItem,
      };
    }
    isEdit.value = true;
  }

  function change() {
    isEdit.value = true;
  }
  //域名协议更改
  async function domainSchemeChange(index: number, domainIndex: number) {
    await forms.value[index].validateFields([['domainInfos', domainIndex, 'name']]);
    isEdit.value = true;
  }
  const useStore = useSystemStatusStoreWithOut();
  watch(
    () => isEdit.value,
    (nVal) => {
      useStore.setIsDataChanged(nVal);
    },
    {
      immediate: false,
    },
  );
  async function save() {
    let param = _.cloneDeep(data.value);
    const validationResults = await Promise.all(
      forms.value.map(async (item: any) => {
        try {
          await item.validate();
          return true;
        } catch (e) {
          console.error(e);
          return false;
        }
      }),
    );
    const allFormsValid = validationResults.every((result) => result === true);
    param.oauth2ParamsInfos.map((item: Recordable) => {
      item.clientRegistrations.map((client: Recordable) => {
        client.scope = client.scope.map((value: any) => value.text);
      });
    });
    if (allFormsValid) {
      try {
        await postOauth2Setting(param);
        isEdit.value = false;
      } catch (e) {
        console.error('修改OAuth2设置失败', e);
      }
    } else {
      createMessage.error('有必填项为空，或格式不正确');
    }
  }
</script>

<style lang="less" scoped>
  .ant-collapse :deep(.ant-collapse-item > .ant-collapse-header) {
    align-items: center;
  }
</style>
